<template>
  <VPage class="h-[100%]">
      <div class="h-[100%] relative mx-[8px]">
        <div class="flex flex-col overflow-hidden h-[100%] mb-[8px]">
          <div class="bg-[var(--base-color)] rounded-[8px] mb-[8px] py-[16px]">
            <div class="flex text-[14px] items-start mb-[8px]">
              <span class="whitespace-nowrap pt-[4px]">常用服务商：</span>
              <el-checkbox-group v-model="checkList">
                <el-checkbox
                  v-for="item in optionData"
                  :key="item.logistics_id"
                  :label="item.logistics_id"
                  class="check-color"
                >
                  {{ item.logistics_name }}
                </el-checkbox>
              </el-checkbox-group>
            </div>
            <el-input
              :autosize="{ minRows: 6, maxRows: 10 }"
              type="textarea"
              v-model="queryNo"
              show-word-limit
              clearable
              placeholder="请输入需要查询的单号，每行一个，一次性可查30个"
            />
            <div class="mt-[8px]">
              <el-button type="primary" :loading="loading" @click="handleQuery">
                查询
              </el-button>
            </div>
          </div>

          <div
            class="flex flex-1 min-h-0 flex-col bg-[var(--base-color)] rounded-[8px] relative px-[8px] pt-[8px]"
          >
            <!-- <ActionBar :actions="actions" /> -->
            <vxe-grid ref="tableRef" v-bind="tableOptions" :loading="loading">
              <template #operation="{ row }">
                <el-button
                  link
                  type="primary"
                  v-hasPermi="[logisticsManageAuthList.track_package.track]"
                  @click="handleLocus(row)"
                >
                  物流轨迹
                </el-button>
              </template>
            </vxe-grid>
          </div>
          <LogisticsDetailsDialog
            v-model="detailVisible"
            :items="selectItem"
            @close="selectItem = null"
          />
        </div>
      </div>
  </VPage>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
import ActionBar from "@/components/ActionBar/index.vue";

import LogisticsDetailsDialog from "./components/LogisticsDetailsDialog/index.vue";
import { logisticsManageAuthList } from "@/Auth/logistics-manage.js";
import { overallOptions } from "@/api/public";
import { strHump } from "@/utils/index";
import { quickOrderList, deleteTrack } from "./api/index";

const queryNo = ref("");
const loading = ref(false);
const tableRef = ref();
const detailVisible = ref(false);
const selectItem = ref();
const checkList = ref([]);
const optionData = ref([]);

const { proxy } = getCurrentInstance();

onMounted(() => {
  getOptions();
});

const getOptions = async () => {
  try {
    const params = "map.logistics";
    const { data } = await overallOptions({ params });
    if (data[strHump(params)]) {
      optionData.value = data[strHump(params)];
    }
  } catch (e) {
    console.error(e);
  }
};

const handleQuery = () => {
  tableRef.value.commitProxy("query");
};

const handleReq = async (page) => {
  if (!queryNo.value.trim()?.length) {
    ElMessage.warning("请输入快递单号");
    return;
  }
  try {
    loading.value = true;
    const query_no = queryNo.value
      .split("\n")
      .filter((n) => n.toString().trim().length);

    const { code, message, data, total } = await quickOrderList({
      query_no,
      ...page,
      logistics_id: checkList.value,
    });
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    ElMessage.success("查询成功");
    return { data, total };
  } catch (e) {
    console.error(e);
  } finally {
    loading.value = false;
  }
};

const tableOptions = reactive({
  pagerConfig: { pageSize: 20 },
  round: true,
  autoHidden: true,
  height: "auto",
  columnConfig: {
    resizable: true,
  },
  columns: [
    { fixed: "left", width: 50, type: "checkbox" },
    {
      fixed: "left",
      title: "快递单号",
      minWidth: 120,
      field: "tracking_number",
    },
    { title: "发货国家(服务商)", minWidth: 130, field: "shipping_country" },
    { title: "目的地国家", width: 220, field: "destination_country" },
    { title: "运输状态", width: 105, field: "sys_status_text" },
    { title: "订单号", minWidth: 200, field: "customer_order_no" },
    { title: "最后抓取时间", minWidth: 200, field: "api_last_time" },
    { title: "添加时间", minWidth: 200, field: "create_time" },
    { title: "运输时间", minWidth: 200, field: "delivery_time" },
    {
      title: "操作",
      width: 90,
      fixed: "right",
      slots: { default: "operation" },
    },
  ],
  proxyConfig: {
    autoLoad: false, // 是否自动加载查询数据
    props: {
      result: "data",
      total: "total",
    },
    ajax: {
      query: ({ page }) => {
        return handleReq(page);
      },
    },
  },
});

const handleLocus = (item) => {
  selectItem.value = item;
  detailVisible.value = true;
};

const getSelectRows = () => {
  const rows = tableRef.value?.getCheckboxRecords();
  if (!rows?.length) {
    ElMessage({
      showClose: true,
      message: "请至少选择一条数据！",
      type: "warning",
    });
    return [];
  }
  return rows;
};

const handleDelete = async () => {
  const rows = getSelectRows();
  if (!rows.length) return;
  const id = rows.map((n) => n.id);
  proxy?.confirm({
    title: "提示",
    content: (
      <p>
        确认删除选中的
        <span class="text-[#3366F1] px-[4px]">{id.length || 1}</span>
        条数据？
      </p>
    ),
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = "处理中..";
          await deleteTrack({ id });
          ElMessage.success("操作成功");
        } catch (e) {
          console.error(e);
        } finally {
          instance.confirmButtonLoading = false;
          done();
          handleQuery();
        }
      } else {
        done();
      }
    },
  });
};

const actions = [
  // {
  //   label: "删除",
  //   icon: "icon-del text-[#E50113]",
  //   fn: handleDelete,
  //   permission: [logisticsManageAuthList.track_package.delete],
  // },
];
</script>
<style lang="scss" scoped>
.check-color {
  :deep(.el-checkbox__label) {
    color: var(--base-text-color);
  }
}
:deep(.vxe-cell--title) {
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
}
:deep(.vxe-pager) {
  height: 40px;
}
</style>
